//****************************************************************
//* Copyright (c) 2008 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   EconomicSourceLogic.java  $$
//* $$Revision:   1.1  $$
//* $$Author:   JLOPE262  $$
//* $$Date:   Nov 21 2008 14:22:28  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.logic;

import java.sql.Timestamp;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.EconomicSourceDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese02Econsource;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class EconomicSourceLogic {

    private static final String CLASS_NAME = EconomicSourceLogic.class
            .getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * Busca Economic Sources segun code y name para la planta "plant".
     * 
     * @param code
     * @param name
     * @param plant
     * @return Economic Sources que se correspondan con la busqueda. Si code y
     * name son vacios, entonces busca todos los Economic Sources
     * @throws FullEconomicsException
     */
    public Collection<Teese02Econsource> findEconomicSources(String code,
                                                             String name,
                                                             Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "findEconomicSources";
        log.entering(CLASS_NAME, METHOD_NAME);

        EconomicSourceDao dao = new EconomicSourceDao();
        Teese02Econsource economicSource = new Teese02Econsource();
        Collection<Teese02Econsource> ret = null;

        if (StringUtils.isBlank(code)) {
            economicSource.setEese02EconsourceNumberK(null);
        } else {
            economicSource.setEese02EconsourceNumberK(Integer.valueOf(code));
        }
        economicSource.setEese02EconsourceNameN(name);
        economicSource.setEese02PlantCodeC(plant);
        try {
            ret = dao.findEconomicSources(economicSource);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Economic Sources Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.EconomicSource.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return ret;
    }

    /**
     * Da de alta el Economic Source pasado por parametro
     * 
     * @param economicSource
     * Economic Source a dar de alta
     * @param user
     * Usuario que da de alta el Economic Source
     * @throws FullEconomicsException
     */
    public void createEconomicSource(Teese02Econsource economicSource,
                                     FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createEconomicSource";
        log.entering(CLASS_NAME, METHOD_NAME);

        EconomicSourceDao dao = new EconomicSourceDao();
        String[] fields = new String[1];
        Object[] values = new Object[1];

        try {
            fields[0] = "eese02PlantCodeC";
            values[0] = user.getTeesg01Plant();
            Integer lastCode = dao.getMax(new Teese02Econsource(), fields,
                    values, "eese02EconsourceNumberK");
            economicSource.setEese02EconsourceNumberK(lastCode + 1);
            economicSource.setEese02CreateUserC(user.getId());
            economicSource.setEese02LastUpdtUserC(user.getId());
            economicSource.setEese02PlantCodeC(user.getTeesg01Plant());
            economicSource.setEese02CreateS(new Timestamp(System
                    .currentTimeMillis()));
            economicSource.setEese02LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));

            PersistenceUtil.newTransaction();
            dao.createEconomicSource(economicSource);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Economic Source Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.EconomicSource.CREATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Actualiza el Economic Source pasado por parametro
     * 
     * @param economicSource
     * Economic Source a actualizar
     * @param user
     * Usuario que actualiza el Economic Source
     * @throws FullEconomicsException
     */
    public void updateEconomicSource(Teese02Econsource economicSource,
                                     FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "updateEconomicSource";
        log.entering(CLASS_NAME, METHOD_NAME);

        EconomicSourceDao dao = new EconomicSourceDao();
        Teese02Econsource workingCopy = null;

        try {
            PersistenceUtil.newTransaction();

            // XXX Ver si esta bien llamar este clearCache aca
            PersistenceUtil.getPersistenceManager().clearCache();

            workingCopy = dao.getEconomicSourceForUpdate(economicSource
                    .getEese02PlantCodeC(), economicSource
                    .getEese02EconsourceNumberK());
            workingCopy.setEese02LastUpdtUserC(user.getId());
            workingCopy.setEese02LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            workingCopy.setEese02EconsourceNameN(economicSource
                    .getEese02EconsourceNameN());

            PersistenceUtil.commitTransaction();
        } catch (PersistenceException pe) {
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Economic Source Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.EconomicSource.UPDATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Elimina el ecnomicSource pasado por parametro
     * 
     * @param economicSource
     * Economic Source a eliminar
     * @throws FullEconomicsException
     */
    public void deleteEconomicSource(Teese02Econsource economicSource)
            throws FullEconomicsException {

        String METHOD_NAME = "deleteEconomicSource";
        log.entering(CLASS_NAME, METHOD_NAME);

        try {
            PersistenceUtil.newTransaction();

            EconomicSourceDao dao = new EconomicSourceDao();
            dao.deleteEconomicSource(economicSource);

            PersistenceUtil.commitTransaction();
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Delete Economic Source Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.EconomicSource.DELETE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Determina si el Economic Source pasado por parametro puede ser borrado.
     * Esto lo determina segun tenga o no Economics haciendo referencia a el
     * 
     * @param economicSource
     * @return True si puede ser borrado. False en caso contrario
     */
    public boolean economicSourceCanBeDeleted(Teese02Econsource economicSource) {
        return economicSource.getTeese01EconomicCollection().size() == 0;
    }

    /**
     * Determina si ya existe un Economic Source con el nombre "name" pasado por
     * parametro
     * 
     * @param name
     * @param plant
     * @return True si ya existe un Economic Source con el nombre pasado por
     * parametro. False en caso contrario
     * @throws FullEconomicsException
     */
    public boolean economicSourceNameAlreadyExists(String name,
                                                   Teesg01Plant plant)
            throws FullEconomicsException {

        String METHOD_NAME = "economicSourceNameAlreadyExists";
        log.entering(CLASS_NAME, METHOD_NAME);

        Collection<Teese02Econsource> economicSources = null;
        String[] fields = new String[1];
        Object[] values = new Object[1];
        EconomicSourceDao dao = new EconomicSourceDao();

        try {
            fields[0] = "eese02PlantCodeC";
            values[0] = plant;
            economicSources = dao.findAll(new Teese02Econsource(), fields,
                    values);
            for (Teese02Econsource economicSource : economicSources) {
                if (economicSource.getEese02EconsourceNameN().trim()
                        .equalsIgnoreCase(name.trim())) {
                    return true;
                }
            }
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Economic Source find all Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.EconomicSource.FIND_ALL);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return false;
    }
}
